package com.note.es.utils;


import com.note.es.connection.ESConnection;
import com.note.es.entity.IndexEntity;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Objects;

public class IndexUtil {

    private static final Logger logger = LoggerFactory.getLogger(IndexUtil.class);

    /**
     * 创建索引
     *
     * @param indexEntity
     * @return
     * @throws IOException
     */
    public boolean createIndex(final IndexEntity indexEntity) throws IOException {
        boolean isSuccess;
        Objects.requireNonNull(indexEntity, "indexEntity is not null");
        String type = Objects.requireNonNull(indexEntity.getType(), "type is not null");
        String name = Objects.requireNonNull(indexEntity.getName(), "name is not null");
        String mapping = indexEntity.getMappings();
        String setting = indexEntity.getSettings();
        //开始创建库
        CreateIndexRequest request = new CreateIndexRequest(name);
        try {
            if (Objects.nonNull(mapping)) {
                //加载数据类型
                request.mapping(type, mapping, XContentType.JSON);
            }
            if (Objects.nonNull(setting)) {
                //分片数
                request.settings(setting, XContentType.JSON);
            }
            CreateIndexResponse createIndexResponse = ESConnection.getClient()
                    .indices().create(request, RequestOptions.DEFAULT);
            isSuccess = createIndexResponse.isAcknowledged();
        } catch (IOException e) {
            throw e;
        }
        return isSuccess;
    }

    /**
     * 删除索引
     *
     * @param indexName
     * @return
     * @throws IOException
     */
    public boolean deleteIndex(final String indexName) throws IOException {
        boolean isSuccess;
        String name = Objects.requireNonNull(indexName, "name is not null");
        //开始创建库
        DeleteIndexRequest request = new DeleteIndexRequest(name);
        try {
            DeleteIndexResponse deleteIndexResponse = ESConnection.getClient()
                    .indices().delete(request, RequestOptions.DEFAULT);
            isSuccess = deleteIndexResponse.isAcknowledged();
        } catch (IOException e) {
            throw e;
        }
        return isSuccess;
    }

}
